package com.example.carRental.service.impl;

import com.example.carRental.entity.LoginUser;
import com.example.carRental.entity.User;
import com.example.carRental.service.LoginService;
import com.example.carRental.utils.JwtUtil;
import com.example.carRental.utils.R;
import com.example.carRental.utils.RD;
import com.example.carRental.utils.RedisCache;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author 92307
 * @version 1.0
 * @time 2022/3/21
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisCache redisCache;

    @Override
    public RD login(User user) {
//        authenticationManager进行用户认证 , 这里传进去之后会自动到自定义的userDetailsService中进行你自定义的用户名密码校验
//        需要要提前暴露认证器
        Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
//        判断认证是否通过
        if(Objects.isNull(authenticate))throw new RuntimeException("认证失败");
//        认证通过后使用id生成jwt，将jwt存入RespondResult.
//        authentication中的pri字段储存着传入的LoginUser(继承了UserDetails)。
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
//        将完整的用户信息存入redis，userid作为key。
        redisCache.setCacheObject(userId,loginUser);
        return RD.success().putData("token",jwt);
    }

//    退出的登陆
    @Override
    public R logout() {
//        获取SecurityContextHolder中的id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser user = (LoginUser) authentication.getPrincipal();
//        从redis中删除
        redisCache.deleteObject(user.getUser().getId().toString());
        return R.success();
    }
}
